import IRenderer from "../../base/ECSR/IRenderer"
import Entity from "../../base/ECSR/Entity";
import AimComponent from "../components/AimComponent";
import AimPathComponent from "../components/AimPathComponent";
import { BubbleColorType } from "../components/BubbleComponent";
import NotifyMgr, { SelfNotification } from "../../base/notify/NotifyMgr";
import Notifications from "../Notifications";
import Guid from "../../../common/utils/Guid";


export default class AimRenderer extends IRenderer
{
    g:cc.Graphics = null;
    path:cc.Vec2[] = [];

    bubblePrefab: cc.Prefab = null;

    adjustBubbleId: string = "";

    isClear:boolean = false;

    onLoad()
    {
        cc.log("AimRenderer|onLoad");
        this.g = this.node.getComponent(cc.Graphics);
        this.g.lineWidth = 5;
        this.g.strokeColor = cc.Color.RED;
    }

    // 子类需要实现的方法
    OnRender(entity:Entity, dt:number):void 
    {
        let aimPathComponent = entity.GetComponent("AimPathComponent") as AimPathComponent;
        if(aimPathComponent && aimPathComponent.enable)
        {
            if(aimPathComponent.isUpdate)
            {
                this.isClear = false;

                aimPathComponent.isUpdate = false;
                this.path = aimPathComponent.path.slice(0);
                this.DrawAimLine();

                if(aimPathComponent.isFind)
                {
                    cc.log("AimRenderer|---1----");
                    NotifyMgr.Instance().Send(Notifications.RemoveEntity, 
                        new SelfNotification("", [this.adjustBubbleId], this));

                    this.adjustBubbleId = Guid.guid();

                    NotifyMgr.Instance().Send(Notifications.CreateNormalBubble, 
                        new SelfNotification("", [this.adjustBubbleId, aimPathComponent.targetPos], this));
                }
            }
        }
        else // 取消瞄准
        {
            if(!this.isClear)
            {
                this.ClearAimLine();
                // 清空
                cc.log("AimRenderer|---2----");
                NotifyMgr.Instance().Send(Notifications.RemoveEntity, 
                    new SelfNotification("", [this.adjustBubbleId], this));

                this.isClear = true;
            }

        }
    }

    TransformPath()
    {
        for(let i = 0; i < this.path.length; ++i)
        {
            this.path[i] = this.path[i].sub(this.node.getPosition());
        }
    }
    DrawAimLine()
    {
        cc.log("AimRenderer|DrawAimLine");
        this.ClearAimLine();

        this.TransformPath();

        this.g.moveTo(this.path[0].x, this.path[0].y);
        cc.log("AimRenderer|DrawAimLine|" + this.path[0].toString());
        for(let i = 1; i < this.path.length; ++i)
        {
            this.g.lineTo(this.path[i].x, this.path[i].y);
        }
        this.g.stroke();
    }

    ClearAimLine()
    {
        this.g.clear();
    }
}